package com.changanw.jedis.sentinel;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

/**
 * jedis 实现哨兵
 */
public class Sentinel {
    public static void main(String[] args) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(10);
        config.setMaxWaitMillis(1000);
        //哨兵名称
        String master = "mymaster";
        Set<String> sentinels = new HashSet<>();
        //哨兵的地址，有多个哨兵的话就添加多个地址
        sentinels.add("127.0.0.1:26379");
        JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(master, sentinels, config, "12345");
        Jedis jedis = null;
        while (true){
            try {
                jedis = jedisSentinelPool.getResource();
                final String k1 = jedis.get("k1");
                System.out.println(k1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (jedis != null){
                    jedis.close();
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
